package xzl.edu.cn.set.demo;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hamcrest.core.Is;

public class FileDataDemo {
	Logger logger = LogManager.getLogger(FileDataDemo.class);
	Works[] works = new Works[] { new Works("Alice", 'w', 00001, 6611.1), new Works("Bob", 'm', 00002, 7711.1) };

	/**
	 * 数据流写入
	 * 
	 * @param filename文件名
	 */
	public void writeDataFile(String filename) {
		File file = new File(filename);
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(file);
			DataOutputStream out = new DataOutputStream(fos);
			for (int i = 0; i < works.length; i++) {
				out.writeUTF(works[i].name);
				out.writeChar(works[i].sex);
				out.writeLong(works[i].id);
				out.writeDouble(works[i].wage);
			}
			fos.close();
			out.close();
			logger.info("写入完毕！");
		} catch (FileNotFoundException e) {
			logger.info("该文件不存在！");
			e.printStackTrace();
		} catch (IOException e) {
			logger.info("写入失败！");
			e.printStackTrace();
		}

	}

	/**
	 * 数据流读取
	 * 
	 * @param filename 文件名
	 */
	public void readDataFile(String filename) {
		File file = new File(filename);
		try {
			FileInputStream fis = new FileInputStream(file);
			DataInputStream in = new DataInputStream(fis);
			for (int i = 0; i < works.length; i++) {
				String name = in.readUTF();
				char sex = in.readChar();
				long id = in.readLong();
				double wage = in.readDouble();
				Works w = new Works(name, sex, id, wage);
				logger.info(w.toString());
			}
			fis.close();
			in.close();
		} catch (FileNotFoundException e) {
			logger.info("文件不存在！");
			e.printStackTrace();
		} catch (IOException e) {
			logger.info("读取失败！");
			e.printStackTrace();
		}
	}

}
